#!/usr/bin/env python
# -*- coding: utf8 -*-

import os,sys,init

k = init.INIT()
WorkDir = k.WorkDir


def createDir(path,sftp):
    dir = ''
    for i in path.split('/'):
        dir += '/'+i
        try:
            sftp.chdir(dir)
        except:
            sftp.mkdir(dir)
def deleteDir(path,sftp):
    try:
        sftp.chdir(path)
    except:
        return 
    for i in sftp.listdir(path):
        try:
            sftp.chdir(path+'/'+i)
            deleteDir(path+'/'+i,sftp)
        except:
            sftp.remove(path+'/'+i)
    sftp.rmdir(path)

def sync(localpath,remotepath,sftp):
    try:
        if os.path.isdir(localpath):
            for i in os.listdir(localpath):
                if os.path.isdir(localpath+'/'+i):
                    sftp.mkdir(remotepath+'/'+i)
                    sync(localpath+'/'+i,remotepath+'/'+i,sftp)
                else:
                    sftp.put(localpath+'/'+i,remotepath+'/'+i)
        else:
            sftp.put(localpath,remotepath)     
        return 'sync successfully'
    except Exception as err:
        return 'sync failed: %s' % str(err)

def syncDir(localpath,remotepath,sftp):
    deleteDir(remotepath,sftp)
    createDir(remotepath,sftp)
    return sync(localpath,remotepath,sftp)

def installPackage(package,sftp,ssh,tout=60):
    stdin,stdout,stderr = ssh.exec_command('rpm -q --quiet '+package+' && echo ok',timeout=3)
    if not stdout.read():
        if syncDir(WorkDir+'/files/yum.repos.d','/etc/yum.repos.d',sftp).endswith('successfully'):
            stdin,stdout,stderr = ssh.exec_command('yum -y install '+package+' --nogpgcheck > /dev/null && echo ok',timeout=tout)
            if stdout.read():
                return 'Install package %s successfully!' % package
            else:
                errorinfo = stderr.read()
        else:
            errorinfo = 'Yum list sync failed'
        return 'Install package %s failed. Info: %s' % (package,errorinfo)
    return 'Install package %s successfully!' % package

            
def saveToRedis(data,r):
    r.setnx('jobid','0')
    r.incrby('jobid','1')
    job = 'task'+r.get('jobid')
    for i in data.split('\n'):
        key,value = i.strip(',').split(':',1)
        r.hset(job,key,value)
    return job
def getFromRedis(job,r,mode='all'):
    print '执行代码: '+job+'\n'
    print '时间: '+r.hget(job,'time')
    print '节点: '+r.hget(job,'node')
    print '路径: '+r.hget(job,'path')
    print '项目: '+r.hget(job,'project')
    print '运行: '+r.hget(job,'runtime')+' 秒'
    print '操作: '+r.hget(job,'user')
    print '模式: '+r.hget(job,'mode')+'\n'
    for i,c in [['addlist','新增'],['rmlist','删除'],['chlist','更新']]:
        if r.hget(job,i):
            print c+':'
            list = r.hget(job,i).split(',')
            if mode == 'short':
                if len(list) > 5:
                    for i in range(5):
                        print ' '*4+list[i].strip('\'')
                    print '    ...还有 '+str(len(list) - 5)+' 个文件没有显示...'
                else:
                    for i in range(len(list)):
                        print ' '*4+list[i].strip('\'')
            else:
                for i in list:
                    print ' '*4+i.strip('\'')
        else:
            print c+': \n    无'
        print
    if r.hget(job,'mode').find('更新') != -1:
        for i,c in [['add','新增'],['rm','删除'],['ch','更新']]:
            print c+'文件:%3s    成功:%3s    失败:%3s' % (r.hget(job,i+'count'),r.hget(job,i+'sucess'),r.hget(job,i+'failed'))

def format(data):
    result = {}
    for monitor in data:
        if monitor == 'get_time':
            data[monitor] = {'color':'black','status':data[monitor]+'s'}
            continue
        if data[monitor]['status'] == 'Ok':
            data[monitor].update({'color':'green'})
        else:
            data[monitor].update({'color':'red'})
    return data
